package cz.cvut.fel.gfupan.gui.action;

import cz.cvut.fel.gfupan.gui.Session;
import cz.cvut.fel.gfupan.gui.component.Observable;
import cz.cvut.fel.gfupan.gui.tab.AbstractTab;
import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.text.JTextComponent;

public class TextFocusListener extends FocusAdapter {

    private JTextComponent component;
    private Color defaultColor;
    private String text;
    private AbstractTab tab;

    public TextFocusListener(JTextComponent component) {
        this.component = component;
        defaultColor = component.getBackground();
    }

    public TextFocusListener(JTextComponent component, AbstractTab tab) {
        this.tab = tab;
        this.component = component;
        defaultColor = component.getBackground();
    }

    @Override
    public void focusGained(FocusEvent evt) {
        if (tab != null) {
            tab.setActualPosition(component);
        }

        component.selectAll();
        text = component.getText();
        component.setBackground(Color.yellow);
    }

    @Override
    public void focusLost(FocusEvent evt) {
        if (!text.equals(component.getText())) {
            Session.getInstance().hasChanged();
        }
        
        if(component instanceof Observable) {
            ((Observable) component).notifyObservers();
        }
        component.setBackground(defaultColor);
    }
}
